import { $t } from '@vben/locales';

// composables/useDictCache.ts
import { getDepartmentList } from '#/api/sys/department';
import { getMenuList } from '#/api/sys/menu';
import { buildMenuTree } from '#/utils/treetransform';

export type DictType = 'department' | 'menu' | 'position' | 'role';

export const dictCache = reactive(new Map<DictType, any[]>());
const loadingMap = new Map<DictType, boolean>();
const fetchMap: Record<DictType, () => Promise<any[]>> = {
  // 菜单列表
  menu: async () => {
    const menures = await getMenuList({ page: 1, pageSize: 5000, status: 1 });
    const transformTree = buildMenuTree(menures.data, 0);
    const extractTreeInfo = (data: any) =>
      data.map(({ name, id, children }: any) => ({
        label: $t(`sys.menu.${name}`),
        value: id,
        id,
        ...(children && { children: extractTreeInfo(children) }), // 递归处理子节点
      }));

    return extractTreeInfo(transformTree);
  },
  position(): Promise<any[]> {
    throw new Error('Function not implemented.');
  },
  // 部门列表
  department: async () => {
    const departmentres = await getDepartmentList({ page: 1, pageSize: 5000 });
    const transformTree = buildMenuTree(departmentres.data, 0);
    const extractTreeInfo = (data: any) =>
      data.map(({ name, id, children }: any) => ({
        label: name,
        value: id,
        id,
        ...(children && { children: extractTreeInfo(children) }), // 递归处理子节点
      }));
    return extractTreeInfo(transformTree);
  },
  role(): Promise<any[]> {
    throw new Error('Function not implemented.');
  },
};

// 通过 type 来获取缓存的对应的字典数据
export const useDictOptions = async (type: DictType): Promise<any[]> => {
  if (dictCache.has(type)) {
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    return dictCache.get(type)!;
  }

  if (loadingMap.get(type)) {
    // 防止并发重复请求
    return new Promise((resolve) => {
      const timer = setInterval(() => {
        if (!loadingMap.get(type)) {
          clearInterval(timer);
          resolve(dictCache.get(type) || []);
        }
      }, 50);
    });
  }

  loadingMap.set(type, true);
  try {
    const data = await fetchMap[type]();

    dictCache.set(type, data);

    return data;
  } finally {
    loadingMap.set(type, false);
  }
};

// 主动发请求刷新字典
export const refreshDictOptions = async (type: DictType) => {
  const data = await fetchMap[type]();
  dictCache.set(type, data);
  return data;
};
